package com.example.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView view = new ModelAndView();
        view.setViewName("index");
        return view;
    }

    @GetMapping("/toLogin")
    public ModelAndView toLogin() {
        ModelAndView view = new ModelAndView();
        view.setViewName("login");
        return view;
    }

    @PostMapping("/login")
    public ModelAndView login(String username, String password, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("main");
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            HttpSession session = request.getSession(true);
            session.setAttribute("loginUser", username);
            view.addObject("status","登录成功");
        } else {
            view.addObject("status","登录失败");
        }
        view.addObject("username",username);
        return view;
    }
}
